package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @PostMapping
    public R addAddressBook(@RequestBody AddressBook addressBook){
        Long userId = BaseContext.getId();
        addressBook.setUserId(userId);

        addressBookService.save(addressBook);
        return R.success("保存地址成功！");

    }
    @PutMapping("/default")
    public R defaultAddress(@RequestBody AddressBook addressBook){
        Long addressId = addressBook.getId();
        LambdaUpdateWrapper<AddressBook> wrapper=new LambdaUpdateWrapper<>();
        wrapper.set(AddressBook::getIsDefault,0);
        wrapper.eq(AddressBook::getUserId,BaseContext.getId());
        addressBookService.update(wrapper);
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getId,addressBook.getId());
        AddressBook addressBook1 = addressBookService.getOne(queryWrapper);
        addressBook1.setIsDefault(1);
        addressBookService.updateById(addressBook1);

        return R.success("设置成功！");


    }
    @GetMapping("/{id}")
    public R getAddressById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        return R.success(addressBook);

    }
@GetMapping("/default")
    public R getDefalutAddress(){
    Long userId = BaseContext.getId();
    LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
    wrapper.eq(AddressBook::getIsDefault,1);
    wrapper.eq(AddressBook::getUserId,userId);
    AddressBook one = addressBookService.getOne(wrapper);
    return R.success(one);

}
@GetMapping("/list")
public R getAllAddressList(){

    Long userId = BaseContext.getId();

    LambdaQueryWrapper<AddressBook> wrapper=new LambdaQueryWrapper<>();
    wrapper.eq(AddressBook::getUserId,userId);

    List<AddressBook> list = addressBookService.list(wrapper);
    return R.success(list);


}
@DeleteMapping
public R deleteByIds(@RequestParam("ids") List<Long> ids){

   addressBookService.removeByIds(ids);

    return R.success("删除成功！");

}

@PutMapping
public R update(@RequestBody AddressBook addressBook){

        addressBookService.updateById(addressBook);


        return R.success("修改成功！");
    }
}
